package com.zc.study.thread.casThread;

import java.util.concurrent.atomic.AtomicInteger;

public class CasTest {
    public static AtomicInteger numCas  = new AtomicInteger(0);
    public static int num = 0;

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i<2;i++){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            for (int j=0;j<100;j++){
                                //加重度锁,num = 200
                                synchronized (String.class){
                                    num++;
                                }
//                        num++;//不加锁,num!=200,非同步
                            }
                        }
                    }).start();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i<2;i++){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            for (int j=0;j<100;j++){
                                numCas.incrementAndGet();
                            }
                        }
                    }).start();
                }
            }
        }).start();


        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("输出"+num);
        System.out.println("输出cas"+numCas.get());
    }
}
